<?php
/**
 * 活动管理
 * @author cjli
 *
 */
class ActivityAction extends HomeAction
{
    public function _initialize()
    {
        parent::_initialize();
        //使用redis
        import('@.ORG.RedisCluster');
        $this->redis = new RedisCluster();
    }

    //首页
    public function index(){
       redirect(url('activity/seckill'));
    }    

    //秒杀列表
    public function seckill(){
        send_http_status(301);
        redirect(url(''));
        exit;   
        header("Pragma: no-cache");
        header("Cache-Control: no-cache");
        header("Expires: 0");

        global $user,$language_id;
		$data = array(
    		'docTitle' => L('meta_title_seckill'),
    		'docKeywords' => L('meta_keywords'),
    		//'docDescription' => L('meta_description'),
    	);
		$this->assign($data);

        $nowtime = time();
        $info = ActivityModel::getSeckill($nowtime);
        // print_r($info);
        // exit;
        if(!$info){
            send_http_status(404);
            $this->display(C('ERROR_PAGE'));
            exit;
        }

        //计算秒杀状态
        $start_time =  $info['start_time'];
        $end_time =  $info['end_time'];
//        echo date('Y-m-d H:i:s',$start_time);
// echo $start_time-$nowtime;
        if($nowtime < $start_time){
            $info['state'] = 0;
            $info['times'] = $start_time-$nowtime;
            //$info['timeHis'] = ActivityModel::getTime($info['times']);
        }else if($nowtime >= $start_time && $nowtime <= $end_time){
            $info['state'] = 1;
            $info['times'] = $end_time-$nowtime;
            //$info['timeHis'] = ActivityModel::getTime($info['times']);
        }else{
            $info['state'] = 2;
            $info['times'] = 0;
            //$info['timeHis'] = ActivityModel::getTime($info['times']);
        }

        // echo "<pre />";
        // print_r($info);exit;
        $seckill_items_db = D('seckill_items');
        $seckill_items = $seckill_items_db->where(array('fid'=>$info['id']))->select();

        $productList = array();
        foreach($seckill_items as $key=>$val){
            $productList[$key] = ProductModel::get_product_info($val['pid']); 
            $productList[$key]['seckill'] = $val;
            //$productList[$key]['luckurl'] = ActivityModel::getSeckillURL($info, $val['id']);
        }

        // print_r($productList);
        // exit;
        $this->assign('islogin', UserModel::logged());
        $this->assign('issetm', AttributeModel::get_user_measure_mid());

        $this->assign('info',$info);
        $this->assign('productList',$productList);
        $this->assign('logoutSrc', 'src='.base64_encode(url('activity/seckill')));
		
		$productArr = array(649,173,170,474,473);
        $productArrList = ProductModel::get_product_collection_list($productArr);//推荐产品
        $this->assign('productArrList', $productArrList);
		
		
        //$this->display('seckill');
        $this->display('/special/seckilling/index');
    }
     //秒杀ajax处理
    public function seckill_goto(){
       //判断是否有身型数据，如果有直接回到秒杀页面, 没有去设置身型
        if(! AttributeModel::get_user_measure_mid()){
            $url = url('measure/add', 'type=goto&jump_src='.base64_encode('activity/seckill'));
        }else{
            $url = url('activity/seckill');
        }
        header("Location: ".$url);exit;
    } 

    //秒杀ajax处理
    public function seckill_ajax(){

        global $user,$language_id;
        
        if($_REQUEST['timeverify']){

            $fid = $_REQUEST['fid'];
            $nowtime = time();
            $info = ActivityModel::getSeckill($nowtime);

            $times = 0;
            $returninfo = array();
            if($info){
                //抢的数据放redis
                
                $s_info = $this->redis->get('s_info');
                $s_info = unserialize($s_info);
                $is_set_s_items = false;
                if(!$s_info || $s_info['id'] != $info['id'] || $s_info['versions']!=$info['versions'] ){
                    $this->redis->set('s_info', serialize($info));
                    $is_set_s_items = true;
                    $this->redis->remove('s_items');
                }
                if($info['id'] == $fid){
                    //计算秒杀状态
                    $start_time =  $info['start_time'];
                    $end_time =  $info['end_time'];
                    if($nowtime < $start_time){
                        //还在倒计时中
                        $state = 0;
                        $times = $start_time-$nowtime;
                    }else if($nowtime >= $start_time && $nowtime <= $end_time){
                        //正在秒杀中
                        $state = 1;
                        $times = $end_time-$nowtime;
                        $s_items = array();

                        $seckill_items_db = D('seckill_items');
                        $seckill_items = $seckill_items_db->field('id, qty, qty, price')->where(array('fid'=>$info['id']))->select();
                        foreach($seckill_items as $val){
                            $returninfo[$val['id']]['isok'] = 0;
                            $num = D('seckill_result')->where(array('tid'=>$val['id']))->count();
                            //统计下是否还可以秒杀
                            $isget = 0;
                            if(UserModel::logged()){
                                $isget = D('seckill_result')->where(array('tid'=>$val['id'],'user_id'=>$user['id']))->count(); 
                            }
                            if($isget>0){
                                $returninfo[$val['id']]['isok'] = 2; 
                            }else{
                                if($num<$val['qty']){
                                    $returninfo[$val['id']]['luckurl'] = ActivityModel::getSeckillURL($info, $val['id']);
                                    $returninfo[$val['id']]['isok'] = 1; 
                                }                               
                            }
                            $s_item_one = $val;
                            $s_item_one['num'] = $num;
                            $s_items[$val['id']] = $s_item_one;
                        }
                        $old_s_items = $this->redis->get('s_items');
                        if($is_set_s_items || !$old_s_items){
                             $this->redis->set('s_items', serialize($s_items));
                        }
                    }else{
                        //秒杀结束，保持页面不动
                        $state = 2;
                    }
                }else{
                    //换活动了，让页面刷新
                    $state = 3;
                }
            }else{
                $state = 4;
            }
            $info = array(
                'state' => $state, 
                'times' => $times,
                'returninfo' => $returninfo,
                'loginstate' => UserModel::logged(),
            );
            echo json_encode($info);exit;
        }

    }

    //秒杀链接处理
    public function luckurl(){

        global $user,$language_id;
        //是否登陆
        if(!UserModel::logged()){
            $info = array(
                'errNo' => 101, 
                'errStr' => L('seckill_str_1'),//'你还没登陆!',
            );
            echo json_encode($info);exit;
        }
        //是否有身型数据
        $mid = AttributeModel::get_user_measure_mid();
        if(!$mid){
            $info = array(
                'errNo' => 102, 
                'errStr' => L('seckill_str_2'),//'你没绑定身型!',
            );
            echo json_encode($info);exit;
        }

        $fid = $_REQUEST['fid'];
        $tid = $_REQUEST['tid'];
        $sign = $_REQUEST['sign'];
        $nowtime = time();
        
        $seckill = $this->redis->get('s_info');
        $seckill = unserialize($seckill);
        if(!$seckill || $seckill['id'] != $fid ) $seckill = D('seckill')->where(array('id'=>$fid))->find();
        //验证URLsign
        if(!$seckill || $sign != MD5(C('seckill_key').$fid.$tid.$seckill['start_time'])){
            $info = array(
                'errNo' => 103, 
                'errStr' => L('seckill_str_0'),//'参数错误!',
            );
            echo json_encode($info);exit;
        }

        if($nowtime < $seckill['start_time']){
             $info = array(
                'errNo' => 104, 
                'errStr' => L('seckill_state_1'),//'活动还没开始!',
            );
            echo json_encode($info);exit;           
        }
        if($nowtime > $seckill['end_time']){
             $info = array(
                'errNo' => 104, 
                'errStr' => L('seckill_game_over'),//'活动已经结束!',
            );
            echo json_encode($info);exit;           
        }
        
        //统计下是否还可以秒杀
        $isget = D('seckill_result')->where(array('tid'=>$tid,'user_id'=>$user['id']))->count(); 
        if($isget>0){
            $info = array(
                'errNo' => 203, 
                'errStr' => L('seckill_str_3'),//'每件商品只能秒一件!',
            );
            echo json_encode($info);exit;           
        }

        //先做一次判断
        $s_items = $this->redis->get('s_items');
        $s_items = unserialize($s_items);
        if(isset($s_items[$tid])){
            $seckill_items = $s_items[$tid];
            if($seckill_items['num'] >= $seckill_items['qty']){
                $info = array(
                    'errNo' => 202, 
                    'errStr' => L('seckill_str_5'),//'没秒到!',
                );
                echo json_encode($info);exit;                 
            }else{
                //数量加1
                $seckill_items['num'] += 1;
                $s_items[$tid] = $seckill_items;
                $this->redis->set('s_items', serialize($s_items));
            }
        }

        //判断
        $seckill_items = D('seckill_items')->field('id, pid, qty, price')->where(array('id'=>$tid))->find();
        $num = D('seckill_result')->where(array('tid'=>$tid))->count(); 
        if(intval($seckill_items['qty']) > $num){
            $add_data = array(
                'fid'     => $fid,
                'tid'     => $tid,
                'pid'     => $seckill_items['pid'],
                'price'   => $seckill_items['price'],
                'user_id' => $user['id'],
                'time'    => $nowtime,
                'used'    => 0,
            );
            D('seckill_result')->add($add_data);
            //判断是否结束
            ActivityModel::isGameover($fid);
            $info = array(
                'errNo'  => 201, 
                'errStr' => L('seckill_str_4'),//'恭喜秒到了!',
                'pid'    => $seckill_items['pid'],
            );
            echo json_encode($info);exit;            
        }else{
            $info = array(
                'errNo' => 202, 
                'errStr' => L('seckill_str_5'),//'没秒到!',
            );
            echo json_encode($info);exit;        
        }

    }


    public function zskkd(){
        echo "<pre />";
        $seckill = $this->redis->get('s_info');
        $seckill = unserialize($seckill);
        print_r($seckill);
        $s_items = $this->redis->get('s_items');
        $s_items = unserialize($s_items);
        print_r($s_items); 
    }


}